package com.system.common.utils;

import java.util.*;

/**
 * Java代码实现一个方法，给0-9任意一个或者多个设置命中值，例如给1设置1，随机从0-9中获取的概率最高，给1设置2，随机获取的概率次高，依次类推，给1设置5获取概率最低
 *
 * @author wq
 * @date 2023/3/7 10:32
 */
public class ProbabilityRandomizer {

    private static Random rand = new Random();

    public static int randomize(Map<Integer, Integer> probabilityMap) {
        int maxValue = Collections.max(probabilityMap.values());
        int randomValue = rand.nextInt(maxValue) + 1;
        List<Integer> candidates = new ArrayList<>();
        for (Map.Entry<Integer, Integer> entry : probabilityMap.entrySet()) {
            if (entry.getValue() >= randomValue) {
                candidates.add(entry.getKey());
            }
        }
        return candidates.get(rand.nextInt(candidates.size()));
    }

    public static void main(String[] args) {
        Map<Integer, Integer> probabilityMap = new HashMap<>();
        probabilityMap.put(0, 10);
        probabilityMap.put(1, 1);
        probabilityMap.put(2, 2);
        probabilityMap.put(3, 3);
        probabilityMap.put(4, 4);
        probabilityMap.put(5, 5);
        probabilityMap.put(6, 6);
        probabilityMap.put(7, 7);
        probabilityMap.put(8, 8);
        probabilityMap.put(9, 9);
        for (int i = 0; i < 10; i++) {
            System.out.print(randomize(probabilityMap) + " ");
        }
    }
}
